package service

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils"
	"EnjoyWorking/utils/storage"
	"errors"
)

type Department struct {}

func (service *Department) Insert(department *model.Department) error {
	//检验用户是否存在
	var total int64
	if err := storage.MySqlDb().Model(&model.User{}).Where("id = ?", department.ManagerUserId).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_USER_NOT_EXIST.String())
	}

	//检验部门名称是否存在
	if err := storage.MySqlDb().Model(department).Where("name = ?", department.Name).Count(&total).Error; err != nil  {
		return err
	}

	if total != 0 {
		return errors.New(utils.CODE_DEPARTMENT_NAME_DUPLICATE.String())
	}

	return storage.MySqlDb().Create(department).Error
}

func (service *Department) FindList() (int64, []*model.Department, error) {
	var (
		err    error
		total  int64
		result = make([]*model.Department, 0)
	)

	if err = storage.MySqlDb().Model(&model.Department{}).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Select("*").Find(&result).Error; err != nil {
		goto ERR
	}

	for _, v := range result {
		u := &model.User{}
		if err = storage.MySqlDb().Model(u).Where("id = ?", v.ManagerUserId).Find(u).Error; err != nil {
			goto ERR
		}
		v.ManagerUserName = u.UserName
	}

	return total, result, nil
ERR:
	return 0, nil, err
}
